
/// this is the main class which handles differnt types of windows for plugins , modal windows and fixed option windows.
var boxWindow = new Class({
		Extends:WFWindow,					  
		options: $extend({
			width: 200,
			height: 100,
			BtnRefresh: false,
			BtnHelp: false,
			BtnClose: true,
			BtnMin: true,
			BtnMax: false,
			BtnSettings: true,
			BtnSettingsText: true,
			alwaysShowBtns:true,
			hasIcon:false,
			uniqueCss: true,        //unique css name for this widget newly added
			draggable: true,
			dragAnimation:false,
			splitPattern:"`~;",
			title: "Box",
			name: "",
			// myID: "", // commented by TT. We have duplicated myid.
			modal: false,
			fixed: false
		}, custom_options.boxWindow||{} ),
		
		colNumber:0,
		ordering:0,
		contentid: "",
		captionid: "",
		ttlid: "",
		BtnEditID: "",
		BtnRefreshID: "",
		BtnHelpID: "",
		BtnMinID: "",
		BtnCloseID: "",
		parentid: "",
		boxObject: null,
		myPage: 0,
		myid: 0,
		contentBox:null,
		preview:false,
		tempBoxObject: null,
		contentwidth: 0,
		PrevColumnWidth: 0,

		//// initialize the plugin , set the options
		initialize: function(position,id,showMin,showClose,showSetting,showHelp,allowDrag,uniqueCss,pageNumber,order,widget_key) {
			wincount++;

			//// decide what type of window to show , 3 possibles ...... modal with overlay , fixed at mouse position or dragable blocks
			if(this.options.modal == true){
				if(optopen != "" ) {
					$(optopen).remove();
					optopen = "";
				} 

				this.overLay();
				//-- delay a bit , IE sometimes looses track of things
				this.onFinish.delay(50,this);
				if ($chk($('overlay')))
				{
					$('overlay').addEvents({
						'AfterResize':function() {
							this.ModalAfterResize();
						}.bind(this)
					});
				}
			} else if(this.options.fixed == true) {
				this.fixedBox(this.options.left , this.options.top);
				//-- delay a bit , IE sometimes looses track of things
				this.onFinish.delay(50,this);	
			} else {
				if (this.normalBox(position) == false)
				{
					this.parent(position,this.myid,showMin,showClose,showSetting,showHelp,allowDrag,uniqueCss,pageNumber,order,widget_key);
					return;
				}
                ///////////////////////////////////////////////////////////////////////////////////////////					
                // Terrence 11/24/09, for table layout style
                // If it is table layout, the width and height must be adjusted.
                wfc_layout_adjust_box_property(this.boxObject);
                ///////////////////////////////////////////////////////////////////////////////////////////

				//-- delay a bit , IE sometimes looses track of things
				this.onFinish.delay(50,this);

				if (this.boxObject != null)
				{
					this.boxObject.addEvents({
						'AfterResize':function() {
							this.AfterResize();
						}.bind(this),
						'AfterDrop': function(src, dst) {
							this.AfterDrop(src, dst);
						}.bind(this)
					});
				}
			}
			//alert(this.myid);

			//save the object into the array
			//this.shiftToPage(position);
			
			//set this to false for the modules window.. it read in the closeModal fun to 
			//showModules=false;
		},
		
		//////-- get info regarding the block plugin box, its page # , column # and sequence in the column
		/*
		getPosition: function(){
			var i ;
			var tdx = this.boxObject.getParent();
			var tds = tdx.id;
			var the_length=tds.length;
			var tdn=tds.charAt(the_length-1);
			var tc = tds.substr(4,(the_length - 5));
			var childs = tdx.getChildren();
			var l = childs.length;
			var pn = "";
			var lo = "";
			
			/////// go through all tabs to find the current one
			var alltabs = $('tab_panel').getChildren();
			var ttabs = alltabs.length;
			for(var i = 0 ; i < ttabs ; i++)
			{
				var idd = alltabs[i].id;
				if(idd != 'tab_box' && idd.contains('tab_box')) 
				{
					var mee = idd.replace(/tab_box/i , "");
					if(mee == tc) 
					{
						pnt = $('tab_title'+mee).innerHTML; 
						var spll = pnt.split("<!--");
						pn = spll[0];

						spll = spll[1].split("-->"); 
						var pdata = JSON.decode(html_entity_decode(spll[0]));
	
						lo = pdata.columns;
						pageNumber = (i+1);
					}
				}
			}
			
			////////// find column number by going through the columns
			colNumber = (tdn*1)+1;
			for(i = 0 ; i < l ; i++) {
				if(childs[i].id == this.boxObject.id) break;
			}
			ordering = i+1;


			// create an object to return
			var obj = new Object;
			obj.pn = pn;
			obj.layout = lo;
			obj.page = pageNumber;
			obj.col = colNumber;
			obj.order = ordering;
			obj.name = this.options.name; 

			var rawHTML = modules[counter].boxObject.innerHTML; 
			 
			//new config
			//get the setting of this widget.
			var wid_conf = rawHTML;	//childs[0].innerHTML;
			var wid_conf1 = wid_conf.split("~~");			
			var widget_config = wid_conf1[1].split("~~");

			var final_setting = widget_config[0].split("~");
			
			//alert(final_setting);

			obj.showMin = final_setting[0];
			obj.showClose = final_setting[1];;
			obj.showSetting = final_setting[2];
			obj.allowDrag = final_setting[3];
			obj.uniqueCss= final_setting[4];

			return obj;
		},
		*/
		
		//--- this draws the fixed box, used for tab options and add widgets block etc
		fixedBox: function(left , top , wd){
			if(optopen != "" ) {
				if($defined ($(optopen)) ) $(optopen).remove();
				optopen = "";
			}
			 
			/// create main block div and set properties
			this.boxObject = new Element('div', {'id':'sbox','class':'window'}).injectBefore($('page_header'));	
			optopen = 'sbox'; //-- create a global var , which we used to keep track of current open options box
			$('sbox').setStyle('zIndex', '1000'); 
			$('sbox').setStyle('position', 'absolute'); 
			$('sbox').setStyle('top', top+'px'); 
			$('sbox').setStyle('left', left+'px'); 
			
			if(wd){
				$('sbox').setStyle('width', wd); 
			}else{
				$('sbox').setStyle('width', this.options.width); 
			}
			$('sbox').setStyle('display', 'inline'); 
			
			this.ttlid = 'indiv1';
			this.contentid = 'insetdiv2';
			this.captionid = 'insetdiv';
			this.BtnEditID = 'adivboxs';
			this.BtnRefreshID = 'adivboxr';
			this.BtnHelpID = 'adivboxhelp';
			this.BtnMinID = 'adivboxt';
			this.BtnCloseID = 'adivbox';
			
            
			new Element('div', {'id':'insetdiv'}).injectInside($('sbox'));	
			new Element('table', {'id':'insettbl','class':'plan_table','width':'100%'}).injectInside($('insetdiv'));
			new Element('tbody', {'id':'insettbdl'}).injectInside($('insettbl'));
			new Element('tr', {'id':'insettbltr'}).injectInside($('insettbdl'));
			new Element('td', {'id':'insettbltd1','class':'window_caption_left'}).injectInside($('insettbltr'));
			new Element('td', {'id':'insettbltd2','class':'window_caption_middle'}).injectAfter($('insettbltd1'));
			var tds = new Element('div', {'id':'divtd1','class':'window_caption'}).injectInside($('insettbltd2'));	
			new Element('div', {'id':'indiv1','class':'caption_title'}).injectInside($('divtd1'));	
			//new Element('a', {'events':{'click':function(event){ var event = new Event(event);this.closeNormal(event.target.id) ; }.bind(this)},'id':'adivbox'+wincount,'class':'btn_close','href':'javascript:void(0)'}).injectInside($('divtd1'));	
			if(this.options.BtnClose == true || wd > 0){
				new Element('a', {'events':{'click':function(){ optopen=""; $('sbox').remove(); if($defined ($('overlay'))) $('overlay').remove(); }},'id':'adivbox'+wincount,'class':'btn_close','href':'javascript:void(0)'}).injectInside(tds);	
			}
			new Element('td', {'id':'insettbltd3','class':'window_caption_right'}).injectAfter($('insettbltd2'));
			
			//CONTENT
			this.contentBox = new Element('div', {'id':'insetdiv2','class':'window_content'}).injectInside($('sbox'));	
			
			//FOOTER
			new Element('div', {'id':'fdiv','class':'window_footer'}).injectInside($('sbox'));	
			new Element('table', {'id':'ftbl','class':'plan_table','width':'100%'}).injectInside($('fdiv'));
			new Element('tbody', {'id':'ftbltb'}).injectInside($('ftbl'));
			new Element('tr', {'id':'ftbltr'}).injectInside($('ftbltb'));
			new Element('td', {'id':'ftbltd1','class':'window_footer_left'}).injectInside($('ftbltr'));
			new Element('td', {'id':'ftbltd2','class':'window_footer_middle'}).injectAfter($('ftbltd1'));
			new Element('td', {'id':'ftbltd3','class':'window_footer_right'}).injectAfter($('ftbltd2'));
			$('ftbltd2').setHTML("&nbsp;");
			$('fdiv').setStyle('padding-bottom', '5px'); 
		},
		
		
		///-- this is the plugins box window , u can specify which column u want to put the box in
		normalBox: function(position)
		{
		    if (!wfc_is_table_layout_style(currTabLayout))
			    if ($('cttr'+ wfc_mainScreen.currActive) == null)
				    return false;
			var obox = null;
			var subbox = false;
			var modCss ="";     //default to parent 
			
			if(this.options.uniqueCss !=undefined)
			    if(this.options.uniqueCss==true)
			        modCss =  this.options.name;
			   
			if(position == -1){
				subbox = true;
				position = null;
			}
			
			if(position == undefined) var col = 0;
			else var col = position;

			//find out which is the non-dragbable box. 
			var fixedColumn = getFixedColumn(); 
			
			// -- find out which column has the least boxes 
        if (!wfc_is_table_layout_style(currTabLayout)) {
			var tds = $('cttr'+ wfc_mainScreen.currActive).getChildren().length;
			var lchilds = 1000;
			var n , childs;
			if(position == undefined)
			{
				for(var i = 0 ; i < tds ; i++)
				{					 
					if(fixedColumn !=i)
					{
					 	n = 'cttd' + wfc_mainScreen.currActive + '' + i;					
						childs = $(n).getChildren().length;
						if( childs < lchilds) 
						{
							col = i;
							lchilds = childs;					 
						}
					}
				}
			}
		}
			if(subbox){
				ht = getHeight();
				wd = getWidth();
				posx = (wd/2)-(350/2);
				posy = (ht/2)-(this.options.height/2);
				this.fixedBox(posx , posy , 350);	
				obox = this.contentBox;
				
				var spn = new Element('span' , {} ).injectInside(obox);	
				var im = new Element('img' , {'src' : 'img/default/plus.gif'} ).injectInside(obox);	
				im.setStyles('margin: 0px 4px 0px 0px; vertical-align: middle;');
				
				var ar = new Element('a' , {'href' : 'javascript:void(0)' , 'events' : {'click' : function(coln){ this.shiftToPage(coln) }.bind(this , [col]) }  } ).injectInside(obox);
				ar.setHTML('<b>'+lang.label('menu_add2')+'</b>');
				wincount++;
				this.preview=true;
			}
			
			this.myPage = wfc_mainScreen.currActive;
			this.ordering = (lchilds+1);
			this.colNumber = (col+1);
			//console.log('col : ' + this.colNumber);

            var nm = 'cttd' + wfc_mainScreen.currActive + '' + col;

			if($defined( $(nm) ) == false)  return;
			
			var nmVals = $(nm).getCoordinates();
			
			/// clear column html , we needed this as IE doesnt want to show the border without any html in there
			if($(nm).innerHTML == "&nbsp;") $(nm).setHTML("");
			
			/// draw parent box div
			this.boxObject = new Element('div', {'id':'sbox'+wincount,'class': modCss + 'window'}).injectInside($(nm));	
			this.boxObject.setStyle('position', 'relative'); 
			this.boxObject.setStyle('top', '0px'); 
			this.boxObject.setStyle('left', '0px'); 
    		//$('sbox'+wincount).setStyle('width' , nmVals.width); 
			//$('sbox'+wincount).setStyle('height', this.options.height); 
			//$('sbox'+wincount).setStyle('display', 'inline'); 
			
			this.ttlid = 'indiv1'+wincount;
			this.contentid = 'insetdiv2'+wincount;
			this.captionid = 'insetdiv'+wincount;
			this.BtnEditID = 'adivboxs'+wincount;
			this.BtnRefreshID = 'adivboxr'+wincount;
			this.BtnHelpID = 'adivboxhelp'+wincount;
			this.BtnMinID = 'adivboxt'+wincount;
			this.BtnCloseID = 'adivbox'+wincount;
			

			var hn;	//dragable stuff

			if(this.options.draggable) {
				hn = new Element('div', {'id':'insetdiv'+wincount, 'class':'handler'}).injectInside($('sbox'+wincount));	
				hn.setStyles('cursor:move;');
			}
			else{
				hn = new Element('div', {'id':'insetdiv'+wincount, 'class':'noneHandler'}).injectInside($('sbox'+wincount));	
			}
			
			var insettbl = new Element('table', {'border': '0','events': !this.options.alwaysShowBtns?
											{'mouseover':function(){ 
														var c = this.id.replace(/insettbl/i , ""); ; 
														if( $defined($('adivboxt'+c)) ) $('adivboxt'+c).setStyle('display','');
														if( $defined($('adivboxr'+c)) ) $('adivboxr'+c).setStyle('display','');
														if( $defined($('adivbox'+c)) ) $('adivbox'+c).setStyle('display','');
														if( $defined($('adivboxs'+c)))  $('adivboxs'+c).setStyle('display','');
													},
											'mouseout':function(){ 
														var c = this.id.replace(/insettbl/i , ""); ; 
														if( $defined($('adivboxt'+c))  )$('adivboxt'+c).setStyle('display','none');
														if( $defined($('adivboxr'+c))  ) $('adivboxr'+c).setStyle('display','none');
														if( $defined($('adivbox'+c))  ) $('adivbox'+c).setStyle('display','none');
														if( $defined($('adivboxs'+c)) ) $('adivboxs'+c).setStyle('display','none');
													}		
											}:{} , 
											'id':'insettbl'+wincount,
											'class':'plan_table',
											'width':'100%'}).injectInside(hn);
			
			var intb1 = new Element('tbody', {'id':'insettbdl'+wincount}).injectInside(insettbl);
			var intr = new Element('tr', {'id':'insettbltr'+wincount}).injectInside(intb1);
			var intd1 = new Element('td', {'id':'insettbltd1'+wincount,'class': modCss + 'window_caption_left'}).injectInside(intr);
			var intd2 = new Element('td', {'id':'insettbltd2'+wincount,'class': modCss + 'window_caption_middle'}).injectAfter(intd1);
			var divtd = new Element('div', {'id':'divtd1'+wincount,'class': modCss + 'window_caption'}).injectInside(intd2);	
			var indiv = new Element('div', {'id':'indiv1'+wincount,'class': modCss + 'caption_title'}).injectInside(divtd);	
			
			var intd3 = new Element('td', {'id':'insettbltd3'+wincount,'class': modCss + 'window_caption_right'}).injectAfter($('insettbltd2'+wincount));
			
			// toogle min max button
			// var adivboxt = new Element('a', {'events':{'click':function(event){ var event = new Event(event);toggleview(event.target.id) ; }},'id':'adivboxt'+wincount,'class': modCss + 'btn_hide','href':'javascript:void(0)'}).injectInside(divtd);
        
			// close button
			var adivbox;			 
			if(this.options.BtnClose)
				adivbox = new Element('a', {'events':{'click':function(event){ var event = new Event(event); this.closeNormal(event.target.id) ; }.bind(this)},'id':'adivbox'+wincount, title: lang.label('widget_btn_close'), 'class': modCss+ 'btn_close','href':'javascript:void(0)'}).injectInside(divtd);	
			else
				adivbox = new Element('span', {'id':'adivbox'+wincount, 'class': 'blank','href':'javascript:void(0)'}).injectInside(divtd);	

			var adivboxt;

			if(this.options.BtnMin)
				adivboxt = new Element('a', {'events':{'click':function(event){ var event = new Event(event);toggleview(event.target.id) ; }},'id':'adivboxt'+wincount, title: lang.label('widget_btn_min'), 'class': modCss + 'btn_hide','href':'javascript:void(0)'}).injectInside(divtd);
			else
				adivboxt = new Element('span',{'id':'adivboxt'+wincount,'class': 'blank'}).injectInside(divtd);

			//this is to save the widgets setting in it self. We will read this later when saving this widget
			var setting_html = this.options.splitPattern+ this.options.BtnMin +"~"+ this.options.BtnClose +"~"+ this.options.BtnSettings +"~"+ this.options.BtnHelp +"~"+this.options.draggable +"~"+ this.options.uniqueCss +this.options.splitPattern;
			/* //roger version
			var setting_html = "`~;"+ this.options.BtnMin +"~"+ this.options.BtnClose +"~"+ this.options.BtnSettings +"~"+ this.options.draggable +"~"+ this.options.uniqueCss +"`~;"; 
			// soros version
			var setting_html = "~~"+ this.options.BtnMin +"~"+ this.options.BtnClose +"~"+ this.options.BtnSettings +"~"+ this.options.draggable +"~"+ this.options.uniqueCss +"~~";
			*/
			//alert(wincount);

			var wid_config = new Element('span', {'id':'xyz'+wincount,'class': 'hiddenEl'}).injectInside(adivbox);	
			wid_config.setHTML(setting_html);

			// help button
			if(this.options.BtnHelp == true){
				new Element('a', {'events':{'click':function(event){ var event = new Event(event);this.showHelpPage(event.target.id) ; }.bind(this)},'id':'adivboxhelp'+wincount, title: lang.label('widget_btn_helppage'), 'class': modCss + 'btn_help','href':'javascript:void(0)'}).injectInside(divtd);	
				$('adivboxhelp'+wincount).setStyle('display', this.options.alwaysShowBtns ? '':'none'); 
			}		
						
			// refresh button
			if(this.options.BtnRefresh == true){
				new Element('a', {'events':{'click':function(event){ var event = new Event(event);this.refreshMod(event.target.id) ; }.bind(this)},'id':'adivboxr'+wincount, title: lang.label('widget_btn_refresh'), 'class': modCss + 'btn_refresh','href':'javascript:void(0)'}).injectInside(divtd);	
				$('adivboxr'+wincount).setStyle('display', this.options.alwaysShowBtns ? '':'none'); 
			}
	
			// settings button

			if(this.options.BtnSettings == true)
			{
				var divboxs = new Element('a', {'events':
                    {'click':function(event){ 
                         //var event = new Event(event); 
                         if (this.options.BtnSettingsText ||
                             this.options.BtnSettingsClass )
                         {
                             var btn = this.boxObject.getElements('.btn_settings')[0]==null ? 
                                        this.boxObject.getElements('.'+modCss+'btn_settings')[0] :
                                        this.boxObject.getElements('.btn_settings')[0];
                             if(!btn.getAttribute('editing') || btn.getAttribute('editing')==''){
                                if(this.options.BtnSettingsText) {
                                    btn.innerHTML = lang.label('widget_btn_setting_close');
                                }
                                if(this.options.BtnSettingsClass) {
                                    btn.parentNode.addClass('editing');
                                }
                                btn.setAttribute('title',lang.label('widget_btn_setting_close'));
                                btn.setAttribute('editing',1);
                             }else{
                                if(this.options.BtnSettingsText) {
                                    btn.innerHTML = lang.label('widget_btn_setting');
                                }
                                if(this.options.BtnSettingsClass) {
                                    btn.parentNode.removeClass('editing');
                                }
                                btn.setAttribute('title',lang.label('widget_btn_setting'));
                                btn.setAttribute('editing','');		
                             }
                         }
                         
                         //event.preventDefault() ; 
                         this.showSettings(this.BtnEditID) ;
                         this.PrevColumnWidth = 0;
                         this.UpdateTitleWidth();
                    }.bind(this)},
                    'id':'adivboxs'+wincount, 
                    'title': lang.label('widget_btn_setting'), 
                    'class': modCss + 'btn_settings',
                    'href':'javascript:void(0)' }).injectInside(divtd);	
				if (this.options.BtnSettingsText)
					divboxs.innerHTML = lang.label('widget_btn_setting') ;
				divboxs.setStyle('display', this.options.alwaysShowBtns ? '':'none'); 
			}

			adivboxt.setStyle('display', this.options.alwaysShowBtns ? '':'none'); 
			adivbox.setStyle( 'display', this.options.alwaysShowBtns ? '':'none');  
			
			//CONTENT
			this.contentBox = new Element('div', {'id':'insetdiv2'+wincount,'class': modCss + 'window_content'}).injectInside(this.boxObject);	
			 
			
			//FOOTER
			var fdiv = new Element('div', {'id':'fdiv'+wincount,'class': modCss + 'window_footer'}).injectInside(this.boxObject);	
			var ftbl = new Element('table', {'id':'ftbl'+wincount,'class': 'plan_table','width':'100%'}).injectInside(fdiv);
			var ftbltb = new Element('tbody', {'id':'ftbltb'+wincount}).injectInside(ftbl);
			var ftbltr = new Element('tr', {'id':'ftbltr'+wincount}).injectInside(ftbltb);
			var ftbltd1 = new Element('td', {'id':'ftbltd1'+wincount,'class': modCss + 'window_footer_left'}).injectInside(ftbltr);
			var ftbltd2 = new Element('td', {'id':'ftbltd2'+wincount,'class': modCss + 'window_footer_middle'}).injectAfter(ftbltd1);
			var ftbltd3 = new Element('td', {'id':'ftbltd3'+wincount,'class': modCss + 'window_footer_right'}).injectAfter(ftbltd2);
			ftbltd2.setHTML("&nbsp;");
			fdiv.setStyle('padding-bottom', '5px'); 
			
			if(subbox) this.boxObject.injectInside(obox);
		},
	
		shiftToPage: function(col){ 
		
			//alert(wfc_mainScreen.currActive);
			var nm = 'cttd' + wfc_mainScreen.currActive + '' + col;
			this.boxObject.injectInside($(nm));
			$(optopen).remove();
			optopen = ""; 
			
			this.closeModal(); 
			/*var iundefined=undefined;  

			//alert('page:' + this.myPage);
			 
			strWidgetsPerPage = this.options.name +':'+ col +':'+ this.myid +':'+ this.options.BtnMin +':'+ this.options.BtnClose +':'+ this.options.BtnSettings +':'+ this.options.draggable +':'+ this.options.uniqueCss +':'+ this.myPage +':'+ this.ordering;
			
			//alert(strWidgetsPerPage);
				  
			wfc_globalModules[currMod]=strWidgetsPerPage; 
			*/
			
			currMod++;	
			
			//var oldSetting=Cookie.get('udpage'+wfc_mainScreen.currActive);

			//if(!oldSetting) oldSetting="";
			
			//Cookie.remove('udpage'+wfc_mainScreen.currActive);

			//set new value then
			//Cookie.set('udpage'+wfc_mainScreen.currActive, oldSetting+strWidgetsPerPage+"|", {duration: 365});
			
			//alert('pc '+ pc);
			modules[pc] = this; 
            						
			this.preview = false;
			this.onFill();
			saveUD();
		},
		
		/// after content is filled create the dragging events
		onFill: function(){
			if(this.options.modal == true || this.options.fixed == true || this.preview == true) return;
			            
			$$('td.droppables').removeEvents();
			
			var fx = null;
			var drag = this.boxObject;
			var childs = drag.getChildren();
			var hndl = undefined;
			// find the title bar, only title bar is draggable
			for(var x = 0 ; x < childs.length ; x++) {
				if(childs[x].getProperty('class') == "handler") {
					hndl = childs[x];       // title bar class is 'handler' 
					break;
				}
			}
		
			if (hndl ==undefined) return;		
			var dragBox = null;
			
            hndl.addEvents({
			   'mousedown' : function(event){
				        // console.log('mousedown');
				        if (iambz == true) return;
				        if (dragBox == null) return;
				        
				        var event = new Event(event);
    					if (event.target.id.contains('adiv')==true) 
	    				    dontfire=true;    // edit, min/max, refresh and delete icon don't fire.
		    			else {
			    		    dontfire=false;   // others, prepare drag drop
			    		    dragBox.start(event);   // ask drag class to start again.
			    		}
			    }
			}); // end of mousedown event handler
			

            // add Drag on hndl (i.e. the title bar of the widget).
			dragBox = new Drag.Move(drag, {
				'handle': hndl, 
				'droppables': $$('td.droppables') ,

				onStart: function(el) {
					// console.log('onStart : el.id=' + el.id + ' dontfire='+dontfire);
					if (dontfire==true) {
					    // don't prpergate event to next and clean up.
					    this.stop();    
                        el.setStyle('zIndex' ,'0'); dragging = false;dragwhich=null; dragcord = null;dragtarget=null;dragstep=0;					    
					} else {
					    // prepare to drag/drop
					    dragcord = el.getCoordinates(); 
					    dragging = true;
					    dragwhich=el.id; 
					}
                },
                
				onBeforeStart: function(el) { 
			        // console.log('onBeforeStart el.id='+el.id);				    
			        if (iambz == true) return;
			        // Terrence 03/13/2009 because onBeforeStart event cannot distinguish element.
			        // It is possible click on drag/drop, refresh, min/max, edit, delete icons.
			        // Must wait mousedown to set dragwhich.
			        if (MooTools['version'].contains('1.2') == true) {
				        if ((dragwhich == undefined) || (dragwhich==null)) {
				            dragwhich=el.id;    // mousedown event haven't fire yet. so return.
				            return;
				        }
				    }
					// this is second time onBeforeStart come in.
					dragwhich=el.id;
					if(dontfire == false){
						if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();	
						dragcord = el.getCoordinates();
						var parenttd = el.getParent();
						var nextdiv = el.getNext('div'); // Avoid IMG element
						
						$$('div.window').setStyle('zIndex' , '0');
						
						el.setStyle('zIndex' , '1000');
						el.setStyle('left' , dragcord.left);
						el.setStyle('top' , dragcord.top);
//						el.setStyle('width' , dragcord.width);  
						el.setStyle('width' , wfc_is_table_layout_style(currTabLayout) ? parenttd.getSize().x - 4: dragcord.width);
						el.setStyle('position' , 'absolute');
							
						if(nextdiv == undefined){
							new Element('div', {'id':'temppp'+dragwhich , 'class':'window'}).injectInside($(parenttd));
						}else{
							new Element('div', {'id':'temppp'+dragwhich , 'class':'window'}).injectBefore($(nextdiv));
						}

//						$('temppp'+dragwhich).setStyle("height" , (dragcord.height - 2));
						$('temppp'+dragwhich).setStyle("height" , wfc_is_table_layout_style(currTabLayout) ? parenttd.getSize().y - 12: dragcord.height-2);
						$('temppp'+dragwhich).setStyle("width" , wfc_is_table_layout_style(currTabLayout) ? parenttd.getSize().x - 4: dragcord.width);
						$('temppp'+dragwhich).setHTML("&nbsp;");
						$('temppp'+dragwhich).setStyle("border" , '1px dotted red');
						
						// Terrence 03/30/09; fix a bug: 
						//  2 widgets in column 1; 2 widget in column 3; move 1 widget from 1 to 3.
						//  Move 1 widget from 1 to 1. The widget will jump to column 3.
						// Because these 3 variable don't re-initial.
						cloneunder = null;
    					cloneover = null;
						cloneinside = null;
						//

					}else{
						if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();	
					}
					el.fireEvent('BeforeDrag', null);
				},  // end of onBeforeStart
				
                // user release mouse.
				onComplete: function(el){
				    // console.log(el, ' onComplete');
                    // el.setStyle('zIndex' ,'0'); dragging = false;dragwhich=null; dragcord = null;dragtarget=null;dragstep=0;
                },

                // user just click and no move
				onCancel: function(el){
				    // console.log(el, ' onCancel');
				    if (iambz == true) return;
					if( dragwhich != undefined && dragwhich != ''){
						$(dragwhich).setStyle('position' , 'relative');
						$(dragwhich).setStyle('left' , 0);
						$(dragwhich).setStyle('top' , 0);
						if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();
    			    }	
					// onComplete, (in Mootools 1.2, it won't fire onComplete event).
					el.setStyle('zIndex' ,'0');
					el.setStyle('width','100%'); 
				    dragging = false;dragwhich=null; dragcord = null;dragtarget=null;dragstep=0;
                    
                    // Jeff Huang 10/06/09
                    // To fix z-index issue:
                    // we will fire an event in the end of dropping
                    el.fireEvent('onEndDrop', 50);  
				},

                onDrag: function(el) {
                    // console.log(el, 'onDrag');
                    // Terrence 12/07/09 for table layout style
                    if (wfc_is_table_layout_style(currTabLayout)) return wfc_drag_box();
                    /////////////////////////////////////////////////////////////////////////////////
					dragstep++; 
					if(dragging && dragstep%4==0){ 
						var pos = $(dragwhich).getCoordinates();
						var childtds = $('cttr'+wfc_mainScreen.currActive).getChildren();
						var incol = null;
						var halfwd = Math.ceil(pos.width/2);
						var maxperc = 0; 
						
						for(var x =0 ; x < childtds.length ; x++){
							var tdobj = childtds[x];
							var tdcord = tdobj.getCoordinates();
								
							var inhere = 0;
							var maxleft = Math.max(tdcord.left , pos.left);
							var maxright = Math.min(tdcord.right , pos.right);
								
							if(maxleft >= tdcord.left){
								inhere = tdcord.right - maxleft;		
							}
								
							if(tdcord.left >= maxleft){
								inhere = maxright - tdcord.left;		
							}
								
							//console.log(' inhere '+ inhere);
								
							if(inhere < 0) continue;
								
							var perc = (inhere/pos.width) * 100;
								
							if(perc > maxperc) {
								maxperc = perc;
								incol = tdobj;
							}
						} 
							
						if(incol == undefined) return false;
						dragtarget = incol.id;

						if(dragtarget == undefined) return false;

						var noDrag = $(dragtarget).hasClass('nondroppables'); 
						if(noDrag) {
							//console.log(' not allowed '+ dragtarget);
							return false;
						} 

					 	// Get all DIVs except IMG element in target column
                        var colchilds = $(dragtarget).getChildren('div'); 
						var coltotals = colchilds.length;
						var minusht = 0;
						var addon = -1;
						var remove = false;
						var updn = 0;
						var i = -1;
						var already = false;
						var ccord;
						
						// Terrence 03/25/09
						// Fix a bug that when drag from 1 child column to others
						//  while drag back to original column, the red box won't show.
						// This is because the child count of original column should be minus 1.
						// Without minus 1; the coltotals is incorrect.
						// Check: if the target column is the original colum of dragwhich, minus one from coltotals.
						if ($defined($(dragwhich).parentNode)) {
						    if ($(dragwhich).parentNode.id == $(dragtarget).id) 
						        if (coltotals == 1) coltotals--;
					    }
					    // 
					 	for( i=0 ; i < coltotals ; i++){
					 	    if (colchilds[i].id == $(dragwhich).id)
					 	        continue;
					 	        
							ccord = colchilds[i].getCoordinates();
							
							if(colchilds[i].id == 'temppp'+dragwhich) {
								//minusht = ccord.height;
								already = true;
								continue;
							}
								
							var halfht = ccord.top + (Math.ceil((ccord.height)/2) - minusht);
							if( (pos.top  > (ccord.top - minusht) && pos.top < halfht)){
								if(cloneshown && cloneover == colchilds[i].id) already = true;
								updn = 1;
								break;
							}
								
							if( (pos.top < (ccord.bottom - minusht) && pos.top > halfht)){
								if(cloneshown && cloneunder == colchilds[i].id)  already = true;
								updn = 2;
								break;
							}
						}
							
							
						if(updn == 0 && coltotals != 0 && already != true){
							var topone = colchilds[0].getCoordinates();
							var bottomone = colchilds[(coltotals - 1)].getCoordinates();
								
							if(pos.top > topone.top){
								i = 0;
								if(cloneshown && cloneover == colchilds[i].id) already = true;
								updn = 1;
							}
								
							if(pos.top > bottomone.bottom){
								i = (coltotals-1);
								if(cloneshown && cloneunder == colchilds[i].id)  already = true;
								updn = 2;
							}
						} 
						
//                        console.log("already:" + already + " i=" + i + " coltotals=" + coltotals + " updn=" + updn);
						if((already == true && i == 1) || i == -1 || coltotals == 0){
							if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();
							new Element('div', {'id':'temppp'+dragwhich}).injectInside($(dragtarget));
							$('temppp'+dragwhich).setStyle("border" , '1px dotted red');
							$('temppp'+dragwhich).setStyle("height" , pos.height);
							$('temppp'+dragwhich).setHTML("&nbsp;");
							cloneshown = true;
							cloneinside = dragtarget;
							cloneunder = null;
							cloneover = null;
							return true;
						}
							
						if( updn == 1 && i > -1){
							if(pos.top > dragcord.top && pos.top < dragcord.bottom && ( colchilds[i].getParent().id == $(dragwhich).getParent().id )) return true;
							
							if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();
							new Element('div', {'id':'temppp'+dragwhich}).injectBefore(colchilds[i]);
							$('temppp'+dragwhich).setStyle("border" , '1px dotted red');
							$('temppp'+dragwhich).setStyle("height" , pos.height);
							$('temppp'+dragwhich).setHTML("&nbsp;");
							cloneshown = true;
							cloneover = colchilds[i].id;
							cloneunder = null;
							cloneinside = null;
							return true;
						}
							
						if( updn == 2 && i  > -1){
							if(pos.top > dragcord.top && pos.top < dragcord.bottom && ( colchilds[i].getParent().id == $(dragwhich).getParent().id )) return true;
							if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();
							new Element('div', {'id':'temppp'+dragwhich}).injectAfter(colchilds[i]);
							$('temppp'+dragwhich).setStyle("border" , '1px dotted red');
							$('temppp'+dragwhich).setStyle("height" , pos.height);
							$('temppp'+dragwhich).setHTML("&nbsp;");
							cloneshown = true;
							cloneunder = colchilds[i].id;
							cloneover = null;
							cloneinside = null;
//							console.log("injectAfter");
							return true;
						}
							
						// console.log(' coming till here '+ dragtarget);
						
						if(already != true){
							cloneshown = false;
							cloneunder = null;
							cloneover = null;
							cloneinside = null;
						}
					}
                },
                
                // Mootools 1.2
		onDrop: function(el, obj){
			if(iambz == true) return ;
			iambz = true;
			var mydragwhich=dragwhich;
			// Terrence 03/15/09; add drag/drop visual effect
			var fx = new Fx.Morph(el, {					        
				duration:wfc_dragdrop_effectDuration,
				wait:false,
				onComplete: function(){
				        // Terrence 12/09/09, for table layout style, when drop complete, do different things.
				        if (wfc_is_table_layout_style(currTabLayout)) 
				            return wfc_drop_complete(el);
				        ////////////////////////////////////////////////////////////////////////////////////
        				if($defined( $('temppp'+mydragwhich) ) ) {
        					    $('temppp'+mydragwhich).remove();
					    }

        				if (mydragwhich != null) {
   			    			// Terrence 03/27/09; add [src, dst] to afterDrop signal.
        				    var dst = null;
   	    		    		var src = $(mydragwhich).parentNode.id;
					        if(this.innerHTML == "&nbsp;") this.setHTML(""); 
					
       						// decide where to insert; maybe no place change. (no inject)
	        				if(cloneinside != undefined){   
			        			dst = cloneinside;
					        	el.injectInside(cloneinside);
       						}else if(cloneover != undefined){
	        					dst = $(cloneover).parentNode.id;
			        			el.injectBefore(cloneover);
					        }else if(cloneunder != undefined){
       							dst = $(cloneunder).parentNode.id;;
	        					el.injectAfter(cloneunder);
			        		}
       						// change the stlye back to normal.
	        				el.setStyle('position','relative');
			        		el.setStyle('left','0px');
					        el.setStyle('top','0px');
       						el.setStyle('width','100%');
	        				el.setStyle('zIndex','0');

       						var tbl = el.id.replace(/sbox/i , '');
        					$('insettbl'+tbl).fireEvent('mouseout');
	        				// Terrence 03/27/09; user defined event for widget handler to redraw.
		        			// src: source column; dst: destination column.
			        		if (dst != null) {
				    	       el.fireEvent('AfterDrop', [src, dst], 100);   
				    	    }
				        } // end of if (dragwhich != null);
					//
					setTimeout("saveUD()" , 100);
					// onComplete, (in Mootools 1.2, it won't fire onComplete event). clean up
					el.setStyle('zIndex' ,'0'); 
					dragging = false;dragwhich=null; dragcord = null;dragtarget=null;dragstep=0;
                    
                    // Jeff Huang 10/06/09
                    // To fix z-index issue:
                    // we will fire an event in the end of dropping
                    el.fireEvent('onEndDrop', 50);  
                    
				} // end of onComplete.
			}); // end of new Fx.Morph

			// start move to destination
			if(wfc_dragdrop_effectOnOff&&$defined( $('temppp'+dragwhich))) {
			    if (wfc_is_table_layout_style(currTabLayout)) {
    				fx.start({
	    				'left': $('temppp'+dragwhich).getParent().getLeft(),
		    			'top': $('temppp'+dragwhich).getParent().getTop()
			    	});
			    }
			    else { 
				    fx.start({
					    'left': $('temppp'+dragwhich).getLeft(),
					    'top': $('temppp'+dragwhich).getTop()
				    });
				}
				dragging = false;  dragcord = null;dragtarget=null; dragstep=0; 
			} else {
				// strange here, must be mouse move out of browser and move in.
				fx.fireEvent('complete', null);
			}
		}   // end of onDrop
		});	// end of Drag.Move
		
			// mootools 1.1
			drag.addEvents({ 
    			'emptydrop' : function(){   // equals to onCancel 1.2
					if( dragwhich != undefined && dragwhich != ''){
						$(dragwhich).setStyle('position' , 'relative');
						$(dragwhich).setStyle('left' , 0);
						$(dragwhich).setStyle('top' , 0);
								
						if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();
				    }	
				 }
			});
            // mootools 1.1			
			$$('td.droppables').each(function(drop, index){
    			drop.addEvents({
					'drop': function(el, obj){
 						if(iambz == true) return ;
						iambz = true;

						if($defined( $('temppp'+dragwhich) ) ) $('temppp'+dragwhich).remove();
						//else return true; 
					 
						if(this.innerHTML == "&nbsp;") this.setHTML(""); 

						if(cloneinside != undefined){
							el.injectInside(cloneinside);
						}else if(cloneover != undefined){
							el.injectBefore(cloneover);
						}else if(cloneunder != undefined){
							el.injectAfter(cloneunder);
						}

						el.setStyle('position','relative');
						el.setStyle('left','0px');
						el.setStyle('top','0px');
						el.setStyle('width','100%');
						el.setStyle('zIndex','0');
						
						var tbl = el.id.replace(/sbox/i , '');
						$('insettbl'+tbl).fireEvent('mouseout');
						el.fireEvent('AfterDrop', [obj]);
						setTimeout("saveUD()" , 50);
					} // end of drop
				}); // end of addEvent.
			}); // end of each.
		},  // end of onFill.
		

		/// draw the overlay we see for modal windows
		overLay: function(){
			new Element('div', {'id':'overlay'}).injectBefore($('page_header'));
			$('overlay').setStyle('position', 'absolute'); 
			$('overlay').setStyle('top', '0'); 
			$('overlay').setStyle('left', '0'); 
			$('overlay').setStyle('zIndex', '90'); 
			//$('overlay').setStyle('width', '100%');
			$('overlay').setStyle('width', getScrollWidth()+"px"); 
			$('overlay').setStyle('height', getScrollHeight()+'px'); 
			$('overlay').setStyle('display', 'block'); 
              // IE6 z-index fix
        if(Browser.Engine.trident  && Browser.Engine.version ==4) {
            var z = $('overlay').getSize();
            var iframe = new Element('iframe', {'id':'overlay_ie6_fix_frame','src':'img/default/1space.gif','frameborder':'0','scrolling':'no'})
                .setStyles({
                'z-index': '-1',
                'position':'absolute',
                'left'   : '-2px',
                'top'    : '-2px',
                'width'  : (z.x+2)+'px',
                'height' : (z.y+2)+'px',
                'filter' : 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)',
                'border' : '0px solid #666'
            });
            $('overlay').adopt(iframe);
        }      
			this.modalWindow();
		},
		
		
		// draw the modal window in the middle of the screen
		modalWindow:function(){

			ht = getHeight();
			wd = getScrollWidth();
			posx = (wd/2)-(this.options.width/2);
			posy = (ht/2)-(this.options.height/2);
			var modCss =this.options.uniqueCss ? this.options.name:'';  

			if(this.options.isBox ==undefined)
			    new Element('div', {'id':'modaloverlay','class':'window'}).injectBefore($('page_header'));	
			else
			    new Element('div', {'id':'modaloverlay','class':'widget_window'}).injectBefore($('page_header'));	

			var overLay = $('modaloverlay');

			overLay.setStyle('position', 'absolute'); 
			overLay.setStyle('zIndex', '100'); 
			
			
			if(this.options.isBox==undefined){ 
				overLay.setStyle('width', this.options.width+'px'); 
			    overLay.setStyle('height', this.options.height+'px'); 
			    
			    overLay.setStyle('top', posy); 
			    overLay.setStyle('left', posx); 
			}else { 
                overLay.setStyle('top' , posy +'px'); 
			    overLay.setStyle('left', posx +'px'); 
            }
			overLay.setStyle('display', 'block'); 
			
			new Element('div', {'id':'insetdiv'}).injectInside(overLay);	
			new Element('table', {'id':'insettbl', 'border': '0', 'class':'plan_table','width':'100%'}).injectInside($('insetdiv'));
			new Element('tbody', {'id':'insettbdl'}).injectInside($('insettbl'));
			new Element('tr', {'id':'insettbltr'}).injectInside($('insettbdl'));
			new Element('td', {'id':'modal_caption_left','class':modCss+'window_caption_left'}).injectInside($('insettbltr'));
			new Element('td', {'id':'modal_caption_middle','class':modCss+'window_caption_middle'}).injectAfter($('modal_caption_left'));
			new Element('div', {'id':'modal_cap','class':modCss+'window_caption'}).injectInside($('modal_caption_middle'));	
			new Element('div', {'id':'modal_cap_title','class':modCss+'caption_title'}).injectInside($('modal_cap'));	
			new Element('a', {'events':{'click':function(){ this.closeModal() ; win=null; }.bind(this)},'id':'adiv','class':modCss+'btn_close','href':'javascript:void(0)'}).injectInside($('modal_cap'));	
			new Element('td', {'id':'modal_caption_right','class':modCss+'window_caption_right'}).injectAfter($('modal_caption_middle'));
            
			//new Element('tbody', {'id':'insettbdl_cont'}).injectInside($('insettbl'));
			//new Element('tr', {'id':'insettbltr_cont'}).injectInside($('insettbdl_cont'));
			//new Element('td', {'id':'insettb', 'class':'widget_window', 'colspan':'3'}).injectInside($('insettbltr_cont'));
			
			if(this.options.isBox ==undefined)
			    this.contentBox = new Element('div', {'id':'modal_content','class':modCss+'window_content'}).injectInside( overLay );	
			else
			    this.contentBox = new Element('div', {'id':'modal_content','class':modCss+'widget_content'}).injectInside( overLay );	
			    
			this.ttlid = 'modal_cap_title';
			this.contentid = 'modal_content';
			this.captionid = 'insetdiv';
			this.BtnEditID = 'adivboxs';
			this.BtnRefreshID = 'adivboxr';
			this.BtnHelpID = 'adivboxhelp';
			this.BtnMinID = 'adivboxt';
			this.BtnCloseID = 'adivbox';
		},
		
		/// close function for fixed windows
		close: function(){
			if(optopen != "" ) {
				if($defined ($(optopen)) ) $(optopen).remove();
				optopen = "";
			}
			saveUD(); 
		},
		
		/// close for plugin windows
		closeNormal: function(whichone){
			whichone = whichone.replace(/adivbox/i , "");
		
			var activeTabModule = wfc_globalModules[wfc_mainScreen.currActive];
			var x = new Array();
			var my_id = this.myid;

			if(activeTabModule) {
				activeTabModule.each(function(module, id)
				{        
					if(module !=undefined){
						if(module.myid!=my_id)
							x[id]=module;	
					 } 
				});
			
				wfc_globalModules[wfc_mainScreen.currActive]=x;
			}
			
			this.whichone=whichone;
			this.saveData(my_id, 'delete', {onResponseOK:this.closeNormalCallBack.bind(this), onResponseERR:this.deleteERRCallBack.bind(this), onFailure:this.deleteFailedCallBack.bind(this)});		//this will delete as well

		},
		
		deleteERRCallBack: function( text, resonseObj) {
			wfc_error_msg(lang.label("msg_deletewidgetfailed"));
			return;	
		},
		deleteFailedCallBack: function(reqObj) {
			wfc_error_msg(lang.label("msg_deletewidgetfailed"));
			return;	
		},
		closeNormalCallBack: function( text, responseObj) {
			if($chk($('sbox'+this.whichone)))
				$('sbox'+this.whichone).remove();
			 
			pgWidgets = (pgWidgets-1);
			pgWidgetsTotal=(pgWidgetsTotal-1);
			modules[this.myid] = 0;

			setTimeout("saveUD()" , 100);
		},
/*
		closeNormalCallBack:function(responseString){
		      var jsonObj=JSON.decode(responseString);
			if(jsonObj.errcode!=0)
			{
				alert(lang.label("msg_deletewidgetfailed"))
				return;	
			}
			if($chk($('sbox'+this.whichone)))
				$('sbox'+this.whichone).remove();
			 
			pgWidgets = (pgWidgets-1);
			pgWidgetsTotal=(pgWidgetsTotal-1);
			modules[this.myid] = 0;

			setTimeout("saveUD()" , 100);
			
		},
*/
		
		/// close for modal windows
		closeModal: function(whichone){ 
		
			if($defined ($('modaloverlay')) ) $('modaloverlay').remove();
			if($defined ($('overlay')) ) $('overlay').remove();				

			//modules[this.options.myID] = 0;  
			//modules[this.myid] = 0;  
			//revert back the original.. because user has closed it
			if(this.options.name=='modModules'){
				//alert(pgWidgetsTotal);
				pgWidgets = pgWidgetsTotal; 
			} 
		},
		
		
		/// fill the content block
		fillContent: function(htmlData){
			$(this.contentid).setHTML(htmlData);	
		},
		
		/// fill the title
		/*
		fillTitle: function(htmlData){
			this.UpdateTitleWidth();

			if($defined($(this.ttlid)))
			{    
				if(this.options.hasIcon) {
                    var _strWidgetDir;
                    if (g_arrUserGeneratedInfoOfWidget[this.options.name] == 1){
                        _strWidgetDir = USER_GENERATED_WIDGET_DIR;
                    }else{
                        _strWidgetDir = modFolder;
                    }
                    var imgURL =homeBase+_strWidgetDir+'/'+this.options.name+'/img/ico.gif';

					var tester=new Image();
					tester.src=imgURL; 

					if(tester.complete) 
						htmlData = '<img align="left" src="'+ imgURL +'"> &nbsp;'+htmlData;
				}
				$(this.ttlid).setAttribute('title',htmlData);
				$(this.ttlid).setHTML(htmlData);
				this.onFill();
			}
		},
		*/
		requestData: function(url, data2 , method , oncomplete){
			var myAjax = new Ajax(url, { method: method, data:data2, onComplete:oncomplete }).request();
		},

		/// ajax data transfer function
		sendData: function(data2 , oncomplete) {
			url = homeBase+UI_DIR+"/"+this.options.name+"/"+ this.options.dbHandler;
			data2 += AddUrlParam();
			var myAjax = new Ajax(url, { method: 'post', data:data2, onComplete:oncomplete }).request();
		},

		//saveData: function(wid, str, oncomplete) {
		saveData: function(wid, str, cb_functions) {
			if( wfc_widgetDataObj.isDataReady() ) {
				if( str == 'delete' ) {
					wfc_widgetDataObj.WdataDelete(wid, cb_functions);
				} else {
					wfc_widgetDataObj.WdataUpdate(wid, str, cb_functions);
                    // if userdata not empty
                    // str = {"title":"TT5","scope":"#all","fushionview":1,"currentSort":5,"currentSortType":"DESC","acceptlevel":1,"sorting":"DeployedCount","product_type":"15.4"}
                    if (str) {
                        //Step 1 : get data from attribute data
                        var data = JSON.decode(this.objectBox.getProperty('data'));
                        //Step 2 : get data from attribute data
                        data.data = htmlentities("[" + JSON.encode(str) + "]");
                        var final_data = JSON.encode(data);
                        // Step : replace \\ to \
                        final_data = final_data.replace(/\\\\/g,'\\');
                        this.objectBox.set('data',final_data);
                    }
				}
			}
/*
			if(ud == "ok")
			{ 
				var modc = new Hash.Cookie(this.options.name, {autoSave: true, path: '/'});
				if(str=='delete')
				{
					modc.set(id, '');
					sendData(dbHandler, JSON.encode({act:'moduledelete', pid:wfc_mainScreen.currActive, wid:id}), oncomplete);
				}
				else
				{
					modc.set(id, str);
					//sendData(dbHandler, "act=module&modname="+this.options.name+"&wid="+id+"&data="+str+"&pid="+ wfc_mainScreen.currActive, gonull);
					sendData(dbHandler, JSON.encode({act:'module', pid:wfc_mainScreen.currActive, wid:id, data:str}), oncomplete);
				}
			}
*/
		},

		getData: function(id) {
			var wdata = wfc_widgetDataObj.getMyWdataData(id);
			if( wdata == null ) {
				return '';
			}
			return wdata;
/*
			//var modc = new Hash.Cookie(this.options.name, {path: '/'});
			//var v = unescape(modc.get(id));
			var v = unescape(wfc_widgetDataObj.getMyWdataData(id));
		 	if(v == undefined) v = ''; 

			var lsRegExp = /\;space\;/g;
			v=String(v).replace(lsRegExp, " "); 	
			
			return unescape(v); 	 
*/
		},
/* TT: we don't parse such dumb format.
		getSetting: function(data , sett){
			var setval = '';
			var spl = data.split("::");
			for(var i = 0 ; i < spl.length ; i++){
				if(spl[i].trim() != ''){
					var spl2 = spl[i].split(":~"); 
					var setname = spl2[0];
					if(setname == sett)	{
						setval = spl2[1];
						break;
					}
				}
			}
			return setval;
		},
*/
		
		onRedraw: function(NeedToUpdateWidth) {
			if (NeedToUpdateWidth)
			{
				this.PrevColumnWidth = 0;
				this.UpdateTitleWidth();
			}
		},
		
		UpdateTitleWidth: function() {
			if (($(this.captionid) == null) || (this.options.modal == true) || $(this.ttlid) == null)
				return;
			//var ColumnWidth1 = wfc_getCurrentColumnWidth(this);
			var ColumnWidth = $(this.captionid).getStyle('width').toInt();
			if ((ColumnWidth <= 0) || isNaN(ColumnWidth))
				return;

			// Width did not change
			if (this.PrevColumnWidth == ColumnWidth)
			{
				this.UpdateTitleWidth.delay(5000, this);
				return;
			}
			this.PrevColumnWidth = ColumnWidth;
			//console.log(this.options.name+' ColumnWidth: '+ColumnWidth);

			//var ObjID = 'adivboxs'+wincount;
			var toolWidth = 20;
			if (this.options.BtnSettings === true)
				toolWidth += this.GetItemWidth(this.BtnEditID);
			if (this.options.BtnRefresh === true)
				toolWidth += this.GetItemWidth(this.BtnRefreshID);
			if (this.options.BtnHelp === true)
				toolWidth += this.GetItemWidth(this.BtnHelpID);
			if (this.options.BtnMin === true)
				toolWidth += this.GetItemWidth(this.BtnMinID);
			if (this.options.BtnClose === true)
				toolWidth += this.GetItemWidth(this.BtnCloseID);
			/*
			var toolWidth = this.GetItemWidth(this.BtnEditID) + 
							this.GetItemWidth(this.BtnRefreshID) + 
							this.GetItemWidth(this.BtnMinID) +
							this.GetItemWidth(this.BtnCloseID) + 
							20;
			*/

			var titleWidth = ColumnWidth - toolWidth;
			$(this.ttlid).setStyle('width', (titleWidth > 0) ? titleWidth : 1 );
			this.UpdateTitleWidth.delay(2000, this);
		},
		
		GetItemWidth: function(ObjID) {
			var bDisplayNone = false;
			var nWidth = 0;
			
			if ($(ObjID) == null)
				return 0;
				
			if (($defined($(ObjID))) && ($(ObjID).getStyle('display') == 'none'))
			{
				$(ObjID).setStyle('display', 'block');
				bDisplayNone = true;
			}
			//console.log(ObjID+' width: '+$(ObjID).getStyle('width').toInt());
			
			nWidth = $(ObjID).getStyle('width').toInt() + 
					$(ObjID).getStyle('paddingLeft').toInt() + 
					$(ObjID).getStyle('paddingRight').toInt() + 
					$(ObjID).getStyle('margin-left').toInt() + 
					$(ObjID).getStyle('margin-right').toInt();
			
			if (bDisplayNone === true)
				$(ObjID).setStyle('display', 'none');
				
			return nWidth;
		},
		
		/// raised when drawing the window is done , exists in the plugin itself
		onFinish: function(){},
		
		ModalAfterResize:function()
        {
        	if($chk($('overlay')))
        	{
                //var ww = Math.max(window.getSize().x, 800);
                
        		$('overlay').setStyle('width',  getScrollWidth()+"px");
        		$('overlay').setStyle('height', getScrollHeight()+"px") ;
        		if($chk($('overlay_ie6_fix_frame')))
        		{
        			var z = $('overlay').getSize();
        			$('overlay_ie6_fix_frame').setStyle('width', (z.x+2)+"px");
        			$('overlay_ie6_fix_frame').setStyle('height',(z.y+2)+"px") ;
        		}
        	}
        	if($chk($('modaloverlay')))
        	{
        		ht = getHeight();
				wd = getScrollWidth();
				posx = (wd/2)-(this.options.width/2);
				posy = (ht/2)-(this.options.height/2);	
        		var overLay = $('modaloverlay');
        		if(this.options.isBox==undefined){
			    	//overLay.setStyle('top', posy); 
			    	overLay.setStyle('left', posx); 
				}else { 
			    	overLay.setStyle('left', posx); 
            	}
        	}
        },
		
		AfterResize: function() {
	    	if (wfc_is_table_layout_style(currTabLayout)) 
	    	    wfc_layout_adjust_box_property(this.boxObject);
	    	    
	    	if(this.contentwidth!=(wfc_getCurrentColumnWidth(this)-4))
	    	{
	    		this.onRedraw(true);
	    		this.contentwidth = wfc_getCurrentColumnWidth(this) - 4;
	    	}
		},
		
		AfterDrop: function(src, dst) {
			if (!wfc_is_table_layout_style(currTabLayout))
				if ($(src).width == $(dst).width) return; // no width change; no need to do anything.
			else
				if ($(src).clientWidth == $(dst).clientWidth) return; // no width change; no need to do anything.
			this.onRedraw(true);
		}
	});
 


	function getFixedColumn()
	{
		var fixedColumn=0;
		var alltabs = $('tab_panel').getChildren();
		var ttabs = alltabs.length;
		for(var f = 0 ; f < ttabs ; f++)
		{
			var idd = alltabs[f].id;
			if(idd != 'tab_box' && idd.contains('tab_box')) 
			{
				pnt = $('tab_title'+wfc_mainScreen.currActive).innerHTML; 
			 
				var spll = pnt.split("<!--");
				pn = spll[0];
				spll = spll[1].split("-->");

				var pdata = JSON.decode(html_entity_decode(spll[0]));
				fixedColumn = pdata.fixedColumn;
				
				break;
			}
		 }
	
	    return fixedColumn;
	}
